import moment from 'moment';
import {NativeModules} from 'react-native';
import DeviceInfo from 'react-native-device-info';
import {Dirs} from 'react-native-file-access';
import ReactNativeBlobUtil from 'react-native-blob-util';
const {HKVisionDeviceModule} = NativeModules;
function numberToBinary(num) {
  if (num < 0) {
    return num;
  }

  // 整数类型的位数
  var number_bit = 8;
  var result = '';

  for (var i = number_bit - 1; i >= 0; i--) {
    // 让 1 左移的位数
    var mask = 1 << i;
    if ((mask & num) === 0) {
      result += '0';
    } else {
      result += '1';
    }
  }

  return result;
}

async function snapUpload(url, completion) {
  const date = moment().format('YYYY-MM-DDHH:mm:ss');
  // 截图
  // 创建一个临时图片文件地址，用于保存截图
  const filename = `${DeviceInfo.getUniqueIdSync()}_${date}.png`;
  const tempPath = `${Dirs.CacheDir}/${filename}`;
  // 截图
  await HKVisionDeviceModule.snap(tempPath, 1, 9, 1920 * 1080);
  const realPath = 'file://' + tempPath;

  var formdata = new FormData();
  formdata.append('relative', 'competition');
  formdata.append('appCode', 'competition');
  ReactNativeBlobUtil.fetch(
    'POST',
    url,
    {
      'Content-Type': 'multipart/form-data',
    },
    [
      {
        name: 'file',
        filename: filename,
        type: 'image/png',
        data: ReactNativeBlobUtil.wrap(realPath),
      },
      // elements without property `filename` will be sent as plain text
      {name: 'relative', data: 'competition'},
      {name: 'appCode', data: 'competition'},
    ],
  )
    .then(resp => {
      return resp.json();
    })
    .then(async res => {
      console.log('res:', res);
      const filePreviewPathFull = res.filePreviewPathFull;
      completion && completion(filePreviewPathFull);
    })
    .catch(async err => {
      // ...
      console.log('err:', err);
      completion(undefined);
    });
}

export default {numberToBinary, snapUpload};
